import {
  SUBMIT,
  FETCH_USER,
  LOGIN,
  LOGIN_REQUEST,
  LOGIN_SUCCESS,
  LOGIN_FAILURE
} from "./actionTypes";

import { updateObject } from "@utils/makeReducerCreator";

const initialState = {
  data: {
    username: "test",
    password: "test"
  },
  loading: false,
  jwt: {
    token: "123"
  }
};

function submit(state, action) {
  return updateObject(state, {
    loading: true,
    data: action.data
  });
}

function loginRequest(state, action) {
  return updateObject(state, {
    loading: true
  });
}

function loginFailure(state, action) {
  return updateObject(state, {
    loading: false,
    error: action.error
  });
}
function loginSuccess(state, action) {
  return updateObject(state, {
    loading: false,
    error: null,
    jwt: {
      token: action.token
    }
  });
}
export function login(state = initialState, action) {
  switch (action.type) {
    case SUBMIT:
      // 点击登录
      return submit(state, action);
    case LOGIN_REQUEST:
      // 正在登录状态
      return loginRequest(state, action);
    case LOGIN_FAILURE:
      // 登录失败
      return loginFailure(state, action);
    case LOGIN_SUCCESS:
      // 登录成功
      return loginSuccess(state, action);
    default:
      return state;
  }
}
